<?php

namespace AdminModule\Helpers;

/**
 * Image
 *
 * @author David
 */
class Image {
    const TYPE_TILE = 'tile';
    const TYPE_SHOWROOM = 'showroom';
    const TYPE_SANITARY = 'sanitary';
    
    private $types = array(
        self::TYPE_TILE,
        self::TYPE_SHOWROOM,
        self::TYPE_SANITARY,
    );
    
    private $name;
    private $type;
    private $config;
    
    public function __construct($name, $type, \AdminModule\Models\ImageConfig $config) {
        if (!in_array($type, $this->types)) {
            throw new \LogicException('Nepodorovaný typ obrázku. Pro definici typu '
                    . 'využijte kostantu z \AdminModule\Helpers\Image::TYPE_*.');
        }
        $this->name = $name;
        $this->type = $type;
        $this->config = $config->getConfigByType($this->type);
    }
    
    public function save($source) {
        if (!\file_exists($source)) {
            throw new \LogicException('Zdrojový soubor obrázku (' . $source . ') neexistuje.');
        }
        
        $image = \Nette\Image::fromFile($source);
        $fullImageDirectory = WWW_DIR . '/' . $this->config->basepath;
        if (!\file_exists($fullImageDirectory)) {
            \mkdir($fullImageDirectory, 0777, true);
        }
        $fullImage = $this->prepareFullImage($image);        
        if (!$fullImage->save($fullImageDirectory . '/' . $this->name)) {
            throw new \LogicException('Ulozeni obrazku selhalo');
        }
        
        $thumbImageDirectory = WWW_DIR . '/' . $this->config->basepath_thumb;
        if (!\file_exists($thumbImageDirectory)) {
            \mkdir($thumbImageDirectory, 0777, true);
        }
        $thumbImage = $this->prepareThumbImage($image);
        if (!$thumbImage->save($thumbImageDirectory . '/' . $this->name)) {
            \unlink(WWW_DIR . '/' . $this->config->basepath . '/' . $this->name);
            throw new \LogicException('Ulozeni miniatury obrazku selhalo');
        }
    }
    
    public function delete() {
        $full = WWW_DIR . '/' . $this->config->basepath . '/' . $this->name;        
        $thumb = WWW_DIR . '/' . $this->config->basepath_thumb . '/' . $this->name;        
        
        if (\file_exists($full)) {
            \unlink($full);
        }        
        if (\file_exists($thumb)) {
            \unlink($thumb);
        }        
    }
    
    private function prepareFullImage(\Nette\Image $image) {
        $maxWidth = $this->config->width;
        $maxHeight = $this->config->height;
        
        return $image->resize($maxWidth, $maxHeight, \Nette\Image::SHRINK_ONLY);
    }
    
    private function prepareThumbImage(\Nette\Image $image) {
        $maxWidth = $this->config->width_thumb;        
        $maxHeight = $this->config->height_thumb;
        
        return $image->resize($maxWidth, $maxHeight, \Nette\Image::SHRINK_ONLY);
    }
}
